<!--
*@Author: QWP
*@Description: 首页过渡页，即所有页面均在次显示
*@Date: 2023-06-19 15:12:06
-->
<template>
  <a-layout
    class="f-h-100 u-transition-page"
    id="transitIndex"
    @click.native="state.showRight = false">
    <a-layout-sider
      class="f-h-100"
      width="220"
      v-model:collapsed="collapsed"
      collapsible
      :trigger="null">
      <Sider
        :data="state.menuData"
        :loading="state.menuLoading"
        mode="inline"
        v-bind:selectedKeys="siderSelectedKeys"
        @click="asideMenuSelect" />
    </a-layout-sider>

    <a-layout direction="vertical">
      <Header
        v-bind:selectedKeys="topSelectedKeys"
        @click="topNavigatClick"
        @noticeClick="state.showNotice = true"
        @emergency="state.showEmergency = true"
        @dropClick="userDropClick"></Header>

      <a-layout-content
        style="padding: 1px 0 0; background-color: #f0f2f7"
        id="gdMain">
        <u-menu-tabs
          :data="state.menuTabsData"
          v-model:activeKey="tabsActive"
          @edit="tabsEdit"
          @change="tabClick"
          @tabClick="tabClick"
          @closeAll="menuTabsCloseAll" />
      </a-layout-content>
    </a-layout>

    <!-- 标签页右键关闭 -->
    <u-right-menu
      v-if="state.showRight"
      :style="{ left: state.rightLeft + 'px', top: state.rightTop + 'px' }"
      @click="rightMenuClick" />

    <!-- 部门通知 -->
    <DeptNotice v-model:open="state.showNotice" />
    
    <!-- 应急通知 -->
    <Emergency
      v-model:open="state.showEmergency"
      @close="state.showEmergency = false" />
    
    <FloatGroupBtn />
  </a-layout>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch, h } from "vue";
import { useHomeStore, useLoginStore } from "@/store";
import { storeToRefs } from "pinia";
import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
import Header from "@/views/index/component/Header.vue";
import Sider from "@/views/index/component/Sider.vue";
import * as menuService from "@/service/system/menu";
import * as enum_types from "@/service/common/enum_types";
import enum_signle_types from "@/service/common/enum_signle_types";
import { chunkArray, disableTreeKeyid, deepForValue, flatArr } from "@/util/format.ts"
import { alertC, urlFile, isValue, jsonCopy } from "@/util/common";
import { tempMenus, _IMenu } from "./menu";
import { cloneDeep } from "lodash";
import { otherEventBus } from '@/util/eventBus'
import DeptNotice from "@/views/index/index/components/deptNotice/Index.vue";
import Emergency from "@/views/index/index/components/emergency/Index.vue";
import UIconFont from "@/components/common/iconfont/IconFont.vue";
import FloatGroupBtn from '@/views/index/floatGroup/Index.vue'

const homeStore = useHomeStore();
const { expand, tabMenu, activeTabMenu, expandKeyPath } = storeToRefs(homeStore);
const { userInfo } = storeToRefs(useLoginStore());
const router = useRouter();
const route = useRoute();

// // 顶部导航栏的选中菜单
const topSelectedKeys = ref<string[]>([""]);
const siderSelectedKeys = ref<string[]>([""]);

let indexPageKey = '1856157256237514753'
const state = reactive({
  logo: urlFile("logo.png"),
  menuLoading: false,
  menuOriginData: [],
  menuData: [],

  menuTabsData: [
    { key: indexPageKey, label: "OA首页", path: "/TransitIndex/Index", closable: false },
    // {key: '0-1', label: '功能导航', path: '/TransitIndex/FunctionNavigate', closable: false},
  ],

  showRight: false,
  rightLeft: 0,
  rightTop: 0,

  showNotice: false, // 显示部门通知
  showEmergency: false, //显示应急通知
});
const tabsActive = ref<string>("0");
const flatMenus = ref<any[]>([]);

// // 侧边栏是否折叠
let collapsed = ref<boolean>(expand);

onMounted(() => {
  // 获取菜单数据
  getMenuDatas();

  otherEventBus.on('updateMenu', () => getMenuDatas())
});

// 顶部菜单栏的点击事件
const topNavigatClick = ({ item, key, keyPath }, isInit?: boolean) => {
  // if (isInit != true) {
    // if (topSelectedKeys.value.includes(key + "")) {
    //   topSelectedKeys.value = [];
    //   state.menuData = cloneDeep(state.menuOriginData);
    //   return;
    // }
  // }
  if (item) {
    topSelectedKeys.value = [key];
    const { originItemValue } = item;
    if (["1", "2", "3", "4"].includes(originItemValue.key)) {
      let tempData = cloneDeep(state.menuOriginData).filter((item) => item.menutypes == originItemValue.key);
      // OA常用
      if (originItemValue.key == "1") {
        if(tempData.length != 0) {
          let oaIndex = (tempData[0]['children'] || []).find(i => i.key == indexPageKey)
          if(oaIndex && isInit != true) {
            asideMenuSelect({  
              item: {
                ...oaIndex,
                originItemValue: cloneDeep(oaIndex)
              },
              key: indexPageKey,
              keyPath: [indexPageKey]
            })
          }
          state.menuData = tempData.length == 0 ? [] : tempData[0]["children"] || [];;
        }
        else {
          state.menuData = []
        }

        
        state.menuData = formatMenuIcon(state.menuData);
        return;
      }
      else if(originItemValue.key == "2") {
        if(tempData.length != 0) {
          let warningIndex = (tempData[0]['children'] || []).find(i => i.key == '1696852837587267636')
          if(warningIndex) {
            asideMenuSelect({  
              item: {
                ...warningIndex,
                originItemValue: cloneDeep(warningIndex)
              },
              key: '1696852837587267636',
              keyPath: ['1696852837587267636']
            })
          }
          state.menuData = tempData.length == 0 ? [] : tempData[0]["children"] || [];
        }
        else {
          state.menuData = []
        }
      }
      else {
        state.menuData = tempData.length == 0 ? [] : tempData.map((item) => item["children"] || [])
          .flat(2);
      }
      state.menuData = formatMenuIcon(state.menuData);
    }
    // 功能导航
    else if (originItemValue.key == "5") {
      tabsActive.value = "0-1";
      routerJump("/TransitIndex/FunctionNavigate");
      saveTabsMenuData(null, tabsActive.value);
    }
  }
};

// 格式化菜单导航
const formatMenuIcon = (data: any[]): any[] => {
  data.forEach((item) => {
    item.icon = h(UIconFont, { type: item["iconurl"] || "icon-a-guizhangzhidu1" });
  });
  return data;
};

// 获取用户的菜单数据
const getMenuDatas = async () => {
  state.menuLoading = true;
  try {
    const res = await menuService.menus();
    if (res.code == 0) {
      let menuData = res.data;
      menuData = deepForValue(cloneDeep(menuData), "key", (data) => data["id"]);
      menuData = formatMenuIcon(menuData);
      homeStore.setAllMenu(menuData)
      state.menuData = menuData;
      state.menuOriginData = menuData;

      flatMenus.value = flatArr(cloneDeep(menuData))

      initTabsMenuData(); // 加载初次展示页面
    }
  } catch (error) {}
  state.menuLoading = false;
};

// 初始化标签页菜单的数据
const initTabsMenuData = (type) => {
  // 如果存在缓存标签页菜单数据
  if (tabMenu.value.length != 0) {
    state.menuTabsData = tabMenu.value;
  }
  // 不存在则显示默认的，并存入缓存
  else {
    saveTabsMenuData(state.menuTabsData, tabsActive.value);
  }

  if (activeTabMenu.value) {
    tabsActive.value = activeTabMenu.value == 0 ? indexPageKey : activeTabMenu.value;
    siderSelectedKeys.value = [tabsActive.value];
  }

  topNavigatClick({ item: { originItemValue: { key: "1" } }, key: "1" }, true);
};

// 用户的下拉菜单点击事件
const userDropClick = ({ item, key, keyPath }) => {
  const path = key.startsWith("5-") ? "/TransitIndex/EmergencyIndex" : "/TransitIndex/Index";
  state.menuTabsData[0]["path"] = path;
  tabsActive.value = "0";
  routerJump(path);
  saveTabsMenuData(state.menuTabsData, tabsActive.value);
};

// 侧边菜单的点击
const asideMenuSelect = ({ item, key, keyPath }) => {
  if (!item) {
    return;
  }
  if (key) {
    siderSelectedKeys.value = [key];
  }

  // 设置展开列
  let expandKeyPath1 = expandKeyPath.value;
  expandKeyPath1[key] = keyPath;
  homeStore.setExpandKeyPath(expandKeyPath1);

  let isExits = state.menuTabsData.some((item) => item.key == key);
  const { originItemValue } = item;
  // 不存在标签页
  if (!isExits) {
    state.menuTabsData.push(originItemValue);
  }
  tabsActive.value = key;
  if (!originItemValue["frameType"]) {
    routerJump(originItemValue["path"]);
  }
  saveTabsMenuData(state.menuTabsData, tabsActive.value);
};

// 菜单标签页的点击
const tabClick = (activeKey) => {
  tabsActive.value = activeKey;
  siderSelectedKeys.value = [tabsActive.value];
  let current = state.menuTabsData.find((i) => i.key == activeKey) || {};
  if (!current["frameType"]) {
    routerJump(current["path"]);
  }
  saveTabsMenuData(null, tabsActive.value);
};

// 菜单标签页的单个移除
const tabsEdit = (data) => {
  let tData = jsonCopy(state.menuTabsData);
  state.menuTabsData = state.menuTabsData.filter((item) => item.key != data);
  let index = tData.findIndex((i) => i.key == data);
  if (index == tData.length - 1) {
    tabsActive.value = state.menuTabsData[index - 1]["key"];
    routerJump(state.menuTabsData[index - 1]["path"]);
  } else {
    tabsActive.value = state.menuTabsData[index]["key"];
    routerJump(state.menuTabsData[index]["path"]);
  }

  saveTabsMenuData(state.menuTabsData, tabsActive.value);
};

// 标签页菜单关闭所有
const menuTabsCloseAll = () => {
  let tData = cloneDeep(state.menuTabsData);
  tData = tData.filter((item) => item.key == indexPageKey);
  state.menuTabsData = tData;
  tabsActive.value = indexPageKey;
  routerJump(tData[0]["path"]);
  saveTabsMenuData(state.menuTabsData, tabsActive.value);
};

// 路由跳转
const routerJump = (path: string) => {
  let query = route.query || {};
  router.push({
    path: path,
    query: {
      t: Date.now(),
    },
  });
};

// 保存标签页相关数据
const saveTabsMenuData = (tabsData: any[] | null, tabsActive: string) => {
  if (tabsData != null) {
    homeStore.setTabMenu(tabsData);
  }
  homeStore.setActiveTabMenu(tabsActive);
};

// 匹配路由跳转的菜单
const matchQueryMenu = (): object | any => {
  const { key, label, path } = route.query

  return flatMenus.value.find((item) => {
    if(key) {
      return item.key == key
    }
    else if(path) {
      return item.path == path
    }
    else if(label) {
      return item.label == label
    }
  })
}

// 路由跳转显示在标签页
watch(
  () => route,
  (nval, oval) => {
    if (nval.query["_tab"]) {
      const { key, label, path } = nval.query
      let menu = matchQueryMenu();
      if (menu) {
        asideMenuSelect({
          item: { originItemValue: menu },
          key: menu.key,
        });
      } else {
        let key = nval.query["label"];
        if (key) {
          asideMenuSelect({
            item: {
              originItemValue: {
                key,
                label: nval.query["label"],
                path: nval.path,
              },
            },
            key,
          });
        }
      }
    }
  },
  { deep: true }
);
</script>

<style lang="scss" scoped></style>
